package org.example.split;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SideOutputDataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;
import org.example.data.WaterSensor;
import org.example.function.WaterSensorMapFunction;

public class SideOutputDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);
        DataStreamSource<String> source = env.socketTextStream("localhost", 9999);
        SingleOutputStreamOperator<WaterSensor> waterSensorStream = source.map(new WaterSensorMapFunction());

        //使用侧输出流，实现分流
        //process是底层算子，逻辑都可以自己处理
        OutputTag<WaterSensor> s1tag = new OutputTag<>("s1", Types.POJO(WaterSensor.class));
        OutputTag<WaterSensor> s2tag = new OutputTag<>("s2", Types.POJO(WaterSensor.class));
        SingleOutputStreamOperator<WaterSensor> process = waterSensorStream.process(new ProcessFunction<WaterSensor, WaterSensor>() {
            @Override
            public void processElement(WaterSensor value, ProcessFunction<WaterSensor, WaterSensor>.Context ctx, Collector<WaterSensor> out) throws Exception {
                String id = value.getId();
                if ("s1".equals(id)) {
                    //s1 放到侧输出流S1中
                    ctx.output(s1tag, value);
                } else if ("s2".equals(id)) {
                    //s2 放到侧输出流S2中
                    ctx.output(s2tag, value);
                } else {
                    //延主流输出
                    out.collect(value);
                }
            }
        });
        //打印主流
        process.print("主流");
        SideOutputDataStream<WaterSensor> sideOutput1 = process.getSideOutput(s1tag);
        sideOutput1.print("s1");
        SideOutputDataStream<WaterSensor> sideOutput2 = process.getSideOutput(s2tag);
        sideOutput2.print("s2");

        env.execute("PartitionDemo");
    }
}
